const { app, BrowserWindow, ipcMain, Tray, Menu, nativeImage } = require('electron')
const path = require("path");
const objectUtils = require('../tools/objectUtils')
const fileService = require('./fileService')
const fileListService = require('./fileListService')
const {height} = require("@mui/system");
const isDev = process.env.NODE_ENV === 'development';
//所有的窗口
let sohoWindows = {}

//创建窗口
function onCreateWindow(options) {
    console.log("----------------------------------")
    console.log(options)
    const source = {
        width: 400,
        height: 300,
        // minWidth: 900,
        // minHeight: 675,
        icon: path.join(__dirname, 'resourse/logo/logo.png'),
        frame: false, //隐藏标题栏
        show: false, //防止闪烁， 加载完后显示
        webPreferences: {
            preload: path.join(__dirname, '../preload.js'),
            contextIsolation: true,
            // nodeIntegration: true,
            sandbox: false,
            webSecurity: false, // 禁用 Web 安全性
            allowRunningInsecureContent: true, // 允许运行不安全内容
        }
    }

    let targetOptions = source;
    if(options?.options) {
        targetOptions = objectUtils.deepMerge(targetOptions, options.options);
    }

    // console.log(targetOptions)

    // Create the browser window.
    let mainWindow = new BrowserWindow(targetOptions)
    mainWindow.setTitle(options?.title ? options.title : "Soho Chat");

    let query = options?.query || {}

    if(options?.url) {
        mainWindow.loadURL(options.url);
    }
    if(options?.file) {
        mainWindow.loadFile(options.file, {query: query})
    }

    mainWindow.setMenu(options?.menu ? options?.menu : null);
    //显示窗口
    mainWindow.once('ready-to-show', ()=>{
        mainWindow.show();
    })

    mainWindow.on('closed', () => mainWindow = null)

    // Open the DevTools.
    if(isDev) {
        mainWindow.webContents.openDevTools()
    }

    //如果窗口存在则关闭窗口
    if(sohoWindows[options.name]) {
        // sohoWindows[options.name].close();
        sohoWindows[options.name] = null;
        delete sohoWindows[options.name];
    }

    //关闭的时候注销纪录
    mainWindow.on('close', (event)=>{
        delete sohoWindows[options.name];
    })

    mainWindow.on('move', ()=>{
        const position = mainWindow.getPosition();
        mainWindow.webContents.send('move', position)
    })

    // 将窗口设置为始终在最上面
    // mainWindow.setAlwaysOnTop(true);

    sohoWindows[options.name] = mainWindow;
    return mainWindow;
}
//获取指定窗口
function getWindowByName(name) {
    if(name in sohoWindows) {
        return sohoWindows[name];
    }
    return null;
}
//resie
function resizeByName(name, size) {
    let mainWindow = getWindowByName(name);
    if(mainWindow) {
        mainWindow.setSize(size[0], size[1])
    }
}

// 关闭指定窗口
const closeWindowByName = (name) => {
    if(sohoWindows[name]) {
        sohoWindows[name].close();
        delete  sohoWindows[name]
    }
}

const closeAllWindow = () => {
    for(let name in sohoWindows) {
        closeWindowByName(name)
    }
}

// 隐藏指定窗口
const hideWindowByName = (name) => {
    if(sohoWindows[name]) {
        sohoWindows[name].hide();
    }
}

// 显示隐藏窗口
const showWindowByName = (name) => {
    if(sohoWindows[name]) {
        sohoWindows[name].show()
    }
}


const hideAllWindow = () => {
    for(let name in sohoWindows) {
        hideWindowByName(name)
    }
}


const showAllWindow = () => {
    for(let name in sohoWindows) {
        showWindowByName(name)
    }
}

// 创建便签窗口
function createNotes (name) {
    let options = {
        options: {
            width: 400,
            height: 300,
            frame: false,
            webPreferences: {
                nodeIntegration: true,
                preload: path.join(__dirname, '../preload.js')
            },
        },
        file: './build/index.html',
        query: {name: name},
        name: name,
    }
    return onCreateWindow(options)
}

//初始化窗口相关
function init() {
    //根据指定参数创建窗口
    ipcMain.on('createWindow', (event, options) => {
        //同一个窗口不允许创建多个
        let win = getWindowByName(options.name);
        if(win && !win.isDestroyed()) {
            win.show();
            return;
        }
        onCreateWindow(options);
    })
    //关闭指定窗口
    ipcMain.on('onCloseWindowWithName', (event, name)=>{
        if(sohoWindows[name]) {
            sohoWindows[name].close();
        }
    })
    //关闭所有窗口
    ipcMain.on('onCloseAllWindow', (event) => {
        BrowserWindow.getAllWindows().map((item)=>{
            item.close();
        })
    })
    //关闭指定窗口以外的窗口
    ipcMain.on('onCloseAllWindowWithoutNames', (event, names) => {
        for (let key in sohoWindows) {
            if(names) {
                if(names.indexOf(key)) {
                    console;
                }
            }
            //关闭窗口
            sohoWindows[key].close();
        }
    })
    //调整窗口尺寸
    ipcMain.on('onResizeWindowByName', (event, name, size)=>{
        resizeByName(name, size);
    })

    //最小化窗口
    ipcMain.handle('minimize-window', (event) => {
        const win = BrowserWindow.fromWebContents(event.sender);
        win.minimize();
    });
    //最大化窗口
    ipcMain.handle('maximize-window', (event) => {
        const win = BrowserWindow.fromWebContents(event.sender);
        if (win.isMaximized()) {
            win.unmaximize();
        } else {
            win.maximize();
        }
    });
    //关闭窗口
    ipcMain.handle('close-window', (event) => {
        const win = BrowserWindow.fromWebContents(event.sender);
        win.close();
    });
    //隐藏窗口
    ipcMain.handle('hide-window', (event)=>{
        BrowserWindow.fromWebContents(event.sender).hide();
    })
    //显示窗口
    ipcMain.handle('show-window', (event)=>{
        BrowserWindow.fromWebContents(event.sender).show();
    })
    //抖动窗口
    ipcMain.on('shake-window', (event)=>{
        console.log("有调用到showWindows")
        shakeWindow(BrowserWindow.fromWebContents(event.sender))
    })

    //监听注册快捷键
    ipcMain.on('readFile', (event, args)=>{
        const {name, callback} = args
        let data = fileListService.getNotes(name)
        if(data) {
            event.sender.send("readFile", data)
            if(data?.x && data?.y) {
                let bound = {x: data.x, y: data.y}
                if(data?.width && data?.height) {
                    bound.width = data.width
                    bound.height = data.height
                }
                BrowserWindow.fromWebContents(event.sender).setBounds(bound)
            }
        }
    })

    ipcMain.on('saveFile', (event, args)=>{
        const {name, content, isLock, isPin} = args;
        // fileService.saveFile(name, content)
        let win = BrowserWindow.fromWebContents(event.sender)
        let bound = win.getBounds()
        fileListService.saveNotes(name, content, bound, isLock, isPin)
    })

    ipcMain.on('delete', (event, args)=>{
        const {name} = args
        fileListService.deleteNotes(name)
        BrowserWindow.fromWebContents(event.sender).close()
    })

    ipcMain.on('new', (event, args)=>{
        createNotes(fileListService.getNewName())
    })
    ipcMain.on('pin', (event, args)=>{
        const {status} = args
        BrowserWindow.fromWebContents(event.sender).setAlwaysOnTop(status)
    })

}


module.exports = {
    init,
    onCreateWindow,
    getWindowByName,
    createNotes,
    closeWindowByName,
    closeAllWindow,
    hideWindowByName,
    showWindowByName,
    hideAllWindow,
    showAllWindow,
};
